package com.gking.centerSystem.service.RootSystem;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gking.centerSystem.common.ProgramException;
import com.gking.centerSystem.common.Result;
import com.gking.centerSystem.entity.*;
import com.gking.centerSystem.mapper.*;
import com.gking.centerSystem.service.Sort.SortService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class RootSystemServiceImpl implements RootSystemService {


    @Resource
    private RootSystemMapper rootSystemMapper;

    @Resource
    private SortMapper sortMapper;

    @Resource
    private SortService sortService;

    @Resource
    private RoutesMapper routesMapper;

    @Resource
    private PermissionsMapper permissionsMapper;

    @Resource
    private RolesMapper rolesMapper;


    @Transactional
    @Override
    public Result<String> addRootSystem(String name, String systemCode) {
        try {
            LambdaQueryWrapper<RootSystem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RootSystem::getSystemCode, systemCode);
            wrapper.eq(RootSystem::getSystemName, name);
            RootSystem system = rootSystemMapper.selectOne(wrapper);
            if (system != null) return Result.error("系统名称或者系统编码已存在！");

            RootSystem sys = new RootSystem();
            sys.setSystemCode(systemCode);
            sys.setSystemName(name);
            rootSystemMapper.insert(sys);

            // 创建系统默认分类
            sortService.createSystemDefaultSort(name, systemCode);

            return Result.success("添加成功！");
        } catch (Exception e) {
            log.error("添加系统失败！{} ", e.getMessage());
            throw new ProgramException();
        }
    }

    @Override
    public Result<List<RootSystem>> getRootSystem() {
        try {
            LambdaQueryWrapper<RootSystem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RootSystem::getIsDelete, 0);
            List<RootSystem> list = rootSystemMapper.selectList(wrapper);

            return Result.success("获取列表成功", list);
        } catch (Exception e) {
            log.error("获取系统列表失败！{} ", e.getMessage());
            throw new ProgramException();
        }
    }

    @Override
    public Result<String> enableSystem(List<Integer> ids, Integer enable) {
        if (ids == null || ids.isEmpty()) return Result.error("id列表不能为空！");
        if (enable != 0 && enable != 1) return Result.error("enable值错误！");

        try {
            LambdaUpdateWrapper<RootSystem> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(RootSystem::getId, ids);
            wrapper.set(RootSystem::getEnable, enable);
            rootSystemMapper.update(null, wrapper);

            return Result.success("操作成功！");
        } catch (Exception e) {
            log.error("启用系统失败！{} ", e.getMessage());
            throw new ProgramException();
        }
    }

    @Transactional
    @Override
    public Result<String> sortAddRootSystemCode(String sortId, String systemCode) {
        if (sortId == null || sortId.isEmpty()) return Result.error("将 分类id 补充完整");

        try {
            LambdaQueryWrapper<Sort> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Sort::getId, sortId);
            queryWrapper.eq(Sort::getIsDelete, 0);

            Sort sort = sortMapper.selectOne(queryWrapper);
            if (sort == null) return Result.error("分类不存在！");

            String code;
            if (systemCode == null || systemCode.isEmpty()) {
                code = sort.getSystemCode();
            } else {
                code = systemCode;

                LambdaQueryWrapper<RootSystem> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(RootSystem::getSystemCode, systemCode);
                wrapper.eq(RootSystem::getIsDelete, 0);
                RootSystem system = rootSystemMapper.selectOne(wrapper);
                if (system == null) return Result.error("系统编码不存在！");
            }
            if (code == null || code.isEmpty()) return Result.error("系统编码不能为空！");

            List<String> sortIds = getSortIds(sortId);
            LambdaUpdateWrapper<Sort> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Sort::getIsDelete, 0);
            updateWrapper.in(Sort::getId, sortIds);
            updateWrapper.set(Sort::getSystemCode, code);

            sortMapper.update(null, updateWrapper);


            // 更新路由表
            LambdaUpdateWrapper<Routes> routesUpdateWrapper = new LambdaUpdateWrapper<>();
            routesUpdateWrapper.in(Routes::getSortId, sortIds);
            routesUpdateWrapper.set(Routes::getSystemCode, code);
            routesMapper.update(null, routesUpdateWrapper);

            // 更新权限表
            LambdaUpdateWrapper<Permissions> permissionsUpdateWrapper = new LambdaUpdateWrapper<>();
            permissionsUpdateWrapper.in(Permissions::getSortId, sortIds);
            permissionsUpdateWrapper.set(Permissions::getSystemCode, code);
            permissionsMapper.update(null, permissionsUpdateWrapper);

            // 更新角色表
            LambdaUpdateWrapper<Roles> roleUpdateWrapper = new LambdaUpdateWrapper<>();
            roleUpdateWrapper.in(Roles::getSortId, sortIds);
            roleUpdateWrapper.set(Roles::getSystemCode, code);
            rolesMapper.update(null, roleUpdateWrapper);

            return Result.success("系统编码添加成功！");
        } catch (Exception e) {
            log.error("系统编码添加失败！{} ", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 通过一个分类id找出该分类下的所有分类id
     *
     * @param id 分类id
     * @return s
     */
    private List<String> getSortIds(String id) {
        List<String> idList = new ArrayList<>();
        idList.add(id);

        // 将分类下的所有分类id查找出来
        LambdaQueryWrapper<Sort> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Sort::getParentId, id);
        queryWrapper.eq(Sort::getIsDelete, 0);
        List<Sort> sorts = sortMapper.selectList(queryWrapper);

        // 递归找出所有id
        for (Sort sort : sorts) idList.addAll(getSortIds(sort.getId()));
        return idList;
    }

}
